package com.huatai.datadevelop.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @Author zhangbenting
 * @Description TODO
 * @Date 2023/9/1 14:03
 * @Version 1.0
 */
public class JDBCUtils {
	/**
	 * 1.定义成员变量 DateSource 连接池
	 */
	private static DataSource ds;

	/**
	 * 2.加载配置文件
	 */
	static {
		try {
			Properties pro = new Properties();
			pro.setProperty("driverClassName",DataProperty.driverClassName);
			pro.setProperty("password",DataProperty.password);
			pro.setProperty("url",DataProperty.url);
			pro.setProperty("username",DataProperty.username);
			pro.setProperty("initialSize",DataProperty.initialSize);
			pro.setProperty("maxActive",DataProperty.maxActive);
			pro.setProperty("minIdle",DataProperty.minIdle);
			//pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
			// 根据工厂类获取数据库连接池对象 SataSource
			ds = DruidDataSourceFactory.createDataSource(pro);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取连接
	 */
	public static Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 释放资源
	 */
	public static void close(Statement stmt, Connection conn) {
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 释放资源； 重载
	 */
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		close(stmt, conn);
	}

	/**
	 * 释放资源； 重载
	 */
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
